<template>
  <!-- 部门余额统计 -->
  <div class="swipe_details">
    <el-form :inline="true" :model="elform" size="mini">
      <el-form-item label="钱包名称">
        <el-select v-model="WalletNo" placeholder="请选择" size="mini" clearable style="width:120px">
          <el-option
            v-for="item in paylist"
            :key="item.walletNo"
            :label="item.walletName"
            :value="item.walletNo"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门" label-width="50px">
        <el-select
          v-model="departmentGuid"
          placeholder="请选择"
          size="mini"
          clearable
          @change="selectdepartment"
          multiple
        >
          <el-option
            v-for="item in departmentoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="userName" placeholder="名称" size="mini" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item label="卡号">
        <el-input v-model="cardNumber" placeholder="卡号" size="mini" clearable style="width: 130px"></el-input>
      </el-form-item>
      <!-- <el-form-item label="编号">
        <el-input v-model="userNumber" placeholder="编号" size="mini" style="width: 130px" clearable></el-input>
      </el-form-item>-->
      <el-form-item class="searchmarigin">
        <el-button type="primary" @click="onSubmit" size="mini" icon="el-icon-search">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onExport" size="mini" icon="el-icon-document-copy">导出</el-button>
      </el-form-item>
      <el-form-item>
        <el-popover width="600" placement="top" trigger="click">
          <el-row>
            <el-col :span="6" v-for="item in Object.keys(formThead)" :key="item">
              <el-checkbox
                :label="formThead[item].label"
                v-model="formThead[item].checked"
                @change="getHeaderDate()"
              ></el-checkbox>
            </el-col>
          </el-row>
          <el-button slot="reference" size="mini" type="primary" icon="el-icon-edit-outline">自定义</el-button>
        </el-popover>
      </el-form-item>
    </el-form>
    <div class="tablemain">
      <el-table
        v-loading="loading"
        :data="detailslist"
        ref="table"
        border
        highlight-current-row
        row-key="id"
        :tree-props="{
          children: 'walletList',
          hasChildren: 'hasChildren',
        }"
        style="width: 100%"
        :header-cell-style="headFirst"
        :cell-style="
          detailsTotal ? (res) => headFirst_col(res, detailslist) : () => {}
        "
      >
        <el-table-column
          prop="walletName"
          label="钱包名称"
          v-if="formThead.walletName.checked"
          min-width="120px"
        ></el-table-column>
        <el-table-column
          prop="userName"
          label="姓名"
          v-if="formThead.userName.checked"
          min-width="120px"
        ></el-table-column>
        <el-table-column
          prop="departmentName"
          label="部门"
          v-if="formThead.departmentName.checked"
          min-width="120px"
        ></el-table-column>
        <el-table-column
          prop="cardNumber"
          label="卡号"
          v-if="formThead.cardNumber.checked"
          min-width="110px"
        ></el-table-column>
        <!-- <el-table-column
          prop="userNumber"
          label="编号"
          v-if="formThead.userNumber.checked"
          min-width="120px"
        ></el-table-column>-->
     <el-table-column prop="accountBalance" label="账上余额(元)" v-if="formThead.accountBalance.checked">
          <template slot-scope="scope">
            <div>{{ scope.row.accountBalance | amountyuan }}</div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="cardSerial" label="卡片流水号" v-if="formThead.cardSerial.checked"></el-table-column> -->
            <el-table-column
          prop="cardBalance"
          label="卡钱包余额(元)"
          v-if="formThead.cardBalance.checked"
          min-width="110px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.cardBalance | amountyuan }}</div>
          </template>
        </el-table-column>
         <el-table-column
            prop="balanceDiff"
            label="差值"
            width="120">
             <template slot-scope="scope">
            <div>{{ scope.row.balanceDiff | amountyuan }}</div>
          </template>
         </el-table-column>
        <el-table-column prop="accountSerial" label="账上流水号" v-if="formThead.accountSerial.checked"></el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          v-if="formThead.updateTime.checked"
          min-width="150px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.updateTime || '' }}</div>
          </template>
        </el-table-column>

     <el-table-column
      label="操作"
      prop="handlebtn"
      width="120">
       <template slot-scope="scope">
        <el-button @click="handleClick(scope.row)" type="text" size="small"  v-if="scope.row.balanceDiff != 0">平账</el-button>
       <el-button @click="handldetails(scope.row)" type="text" size="small">查看详情</el-button>
        <!-- <el-button type="text" size="small">查看详情</el-button> -->
      </template>
    </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChangepage"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="recordCount"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  data() {
    return {
      filename: '个人余额统计报表',
      departmentoptions: [],
      departmentGuid: [],
      userName: '',
      cardNumber: '',
      userNumber: '',
      // 钱包号
      WalletNo: '',   
      // 钱包列表选项
      paylist: [],
      elform: {},
      // 表格渲染数据
      detailslist: [],
      loading: false,
      pageNum: 1,
      pageSize: 20,
      currentPage: 1,
      recordCount: 0,
      searchInfo: {},
      formThead: {
        walletName: {
          label: '钱包名称',
          prop: 'walletName',
          checked: true
        },
        userName: {
          label: '姓名',
          prop: 'userName',
          checked: true
        },
        departmentName: {
          label: '部门',
          prop: 'departmentName',
          checked: true
        },
        cardNumber: {
          label: '卡号',
          prop: 'cardNumber',
          checked: true
        },
        // userNumber: {
        //   label: '编号',
        //   prop: 'userNumber',
        //   checked: true
        // },
        balanceDiff:{
          label: '差值',
          prop: 'balanceDiff',
          checked: true
        },
        cardBalance: {
          label: '卡钱包余额(元)',
          prop: 'cardBalance',
          checked: true
        },
        cardSerial: {
          label: '卡片流水号',
          prop: 'cardSerial',
          checked: false
        },
        accountBalance: {
          label: '账上余额',
          prop: 'accountBalance',
          checked: true
        },
        accountSerial: {
          label: '账上流水号',
          prop: 'accountSerial',
          checked: false
        },
        updateTime: {
          label: '更新时间',
          prop: 'updateTime',
          checked: true
        },
        // handlebtn:{
        //   label:'操作',
        //   prop:'handlebtn',
        //   checked: true
        // },
        },
      //导出数据
      detailslistExportlist: [],
      //汇总合计
      detailsTotal: null,
      administrator:''
    }
  },
// /card/card-balance-details
  mounted() {
    this.administrator = sessionStorage.getItem('administrator')
    this.getPayNumber()
    this.departmentselectlist()

  },
  filters: {},
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid
      }
    }
  },
  methods: {
    // 平账点击
     handleClick(row) {
         this.$http({
        url: this.$http.adornUrl('/card/modify-balance'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
             amount: row.balanceDiff,
             operatorGuid:this.administrator ,
             userGuid: row.userGuid,
             walletNo: this.WalletNo,
           
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          // 请求成功操作
          this.$message({
          showClose: true,
          message: '操作成功',
          type: 'success '
          })
        } else {
          this.$message({
            showClose: true,
            message: data.errorMessage,
            type: 'error'
          })
        }
      })
     },
    //  详情点击
    handldetails(row){
      console.log(row.userGuid);
      console.log(this.WalletNo);
       this.$http({
        url: this.$http.adornUrl('/card/card-balance-details'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
             "searchInfo": {
     userGuid: row.userGuid,
             walletNo: this.WalletNo
    },
             
          },
          messageType: 0
        })
       }).then(({ data }) => {
        if (data.messageCode == 200) {
          console.log(data.messageCode);
          // 请求成功操作
          this.$message({
          showClose: true,
          message: '操作成功',
          type: 'success '
          })
        } else {
          this.message({
            showClose: true,
            message: data.errorMessage,
            type: 'error'
          })
        }
      })
    },
    // 获取钱包
    getPayNumber() {
      this.paylist = []
      this.platformWalletlist = []
      this.$http({
        url: this.$http.adornUrl('/unit/unit-wallet-info-list'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          data.messageContent.map(item => {
            if (Number(item.walletNo) != 100) {
              this.paylist.push(item)
            }
          })
          this.WalletNo =this.paylist.length == 0?'': this.paylist[0].walletNo 
          //  this.paylist[0].walletNo=this.WalletNo
        } else {
          this.$message({
            showClose: true,
            message: data.errorMessage,
            type: 'error'
          })
        }
      })
    },
    // 重新渲染表格
    getHeaderDate() {
      this.$nextTick(() => {
        this.$refs['table'].doLayout()
      })
    },
    //合计查询
    searchtotal() {
      this.searchInfo.unitGuid = this.changeschoolid
      this.detailsTotal = null
      let _this = this
      _this.loading = true
      return new Promise(function(resolve, reject) {
        _this
          .$httpblob({
            url: _this.$httpblob.adornUrl('/card/user-wallet-balance-total'),
            method: 'post',
            data: _this.$httpblob.adornData({
              messageContent: _this.searchInfo,
              messageType: 0
            })
          })
          .then(({ data }) => {
            _this.loading = false
            if (data.messageCode == 200) {
              if (data.messageContent) {
                _this.detailsTotal = {
                  ...data.messageContent,
                  walletName: '合计:',
                  userName: '',
                  accountBalance: data.messageContent.accountBalance,//账上余额
                  accountSerial: '',
                  cardSerial: '', 
                  updateTime: '',
                  balanceDiff:data.messageContent.balanceDiff,//差值
                  // departmentName: '合计：'
                }
              }
              resolve(data.messageContent)
            } 
            else {
              _this.$message.error(data.errorMessage)
              reject(data.errorMessage)
            }
          })
      })
    },
    //部门选择
    departmentselectlist() {
      this.departmentoptions = []
      this.$httpblob({
        url: this.$httpblob.adornUrl('/department/query-department-info'),
        method: 'post',
        data: this.$httpblob.adornData({
          messageContent: {
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          let Arr = data.messageContent
          for (var i = 0; i < Arr.length; i++) {
            let itemobj = {
              value: Arr[i].departmentGuid,
              label: Arr[i].departmentName
            }
            this.departmentoptions.push(itemobj)
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },

    selectdepartment() {},
    // 查询
    async onSubmit() {
      this.pageNum = 1
      this.searchInfo = {}
      this.searchInfo.unitGuid = this.changeschoolid
      this.searchInfo.departmentGuidList = this.departmentGuid
      this.searchInfo.userName = this.userName
      this.searchInfo.cardNumber = this.cardNumber
      this.searchInfo.userNumber = this.userNumber
      this.searchInfo.walletNo = this.WalletNo
      await this.searchtotal()
      this.detailspage()
    },
    // 个人统计余额分页查询
    detailspage() {
      this.loading = true
      this.searchInfo.unitGuid = this.changeschoolid
      this.$httpblob({
        url: this.$httpblob.adornUrl('/card/user-wallet-balance-page'),
        method: 'post',
        data: this.$httpblob.adornData({
          messageContent: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: this.searchInfo
          },
          messageType: 0
        })
      }).then(({ data }) => {
        this.loading = false
        if (
          data.messageContent.data == null ||
          data.messageContent.data.length == 0
        ) {
          this.$message({
            message: '查询成功当前暂无数据',
            type: 'success'
          })
        }
        if (data.messageCode == 200) {
          this.detailslist = data.messageContent.data || []
          this.recordCount = data.messageContent.recordCount
          this.currentPage = data.messageContent.pageNum
          if (this.detailslist != 0) {
            this.detailslist.push({ ...this.detailsTotal })
          }

          for (var i = 0; i < this.detailslist.length; i++) {
            this.detailslist[i].id = 'aa' + [i].toString()
            // this.headerArr.push(this.detailslist[i])
            if (
              this.detailslist[i].walletList != null &&
              this.detailslist[i].walletList.length != 0
            ) {
              for (var j = 0; j < this.detailslist[i].walletList.length; j++) {
                // this.headerArr.push(this.detailslist[i].walletList[j])
                this.detailslist[i].walletList[j].id =
                  'ab' + i.toString() + 'a' + j.toString()
              }
            }
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    async onExport(type) {
      if (this.detailslist.length == 0) {
        this.$message({
          message: '请查询数据后,在进行此操作',
          type: 'warning'
        })
        return false
      }
      await this.outexecelinit()
      if (type == 'print') {
        this.printJS()
      } else {
        this.export2Excel()
      }
    },
    // 打印
    printJS() {
      let someJSONdata = this.detailslistExportlist
      const title = '个人余额统计表'
      this.unitName = sessionStorage.getItem('unitName')
      const properties = []
      // 拿到数据formThead
      for (let key in this.formThead) {
        if (this.formThead[key].checked) {
          properties.push({
            displayName: this.formThead[key].label,
            field: this.formThead[key].prop
          })
        }
      }
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        /**
         * 获取表头的信息
         * @param {*} title 表名
         * @param {*} unitName 单位
         * @param {*} time 时间
         */
        header: this.printHeader(title, this.unitName),
        printable: someJSONdata,
        properties: properties,
        type: 'json',
        // 是否每页都显示头部
        // repeatTableHeader:false,
        headerRow: 1,
        /**
         * 获取页脚的信息
         * @param {*} loginName 制表人：
         * @param {*} time 时间
         */
        endPage: this.printFloor(
          sessionStorage.getItem('username'),
          this.getNowTime('yy-mm-dd hh:mm:ss')
        ),
        //  获取页脚的信息样式
        style: this.printFloorStyle()
      })
    },
    // 个人统计余额分页查询
    outexecelinit() {
      let _this = this
      return new Promise(function(resolve, reject) {
        _this
          .$httpblob({
            url: _this.$httpblob.adornUrl('/card/user-wallet-balance-page'),
            method: 'post',
            data: _this.$httpblob.adornData({
              messageContent: {
                pageNum: 1,
                pageSize: _this.recordCount,
                searchInfo: _this.searchInfo
              },
              messageType: 0
            })
          })
          .then(({ data }) => {
            if (data.messageCode == 200) {
              _this.detailslistExportlist = data.messageContent.data
              _this.detailslistExportlist.push({ ..._this.detailsTotal })

              for (var i = 0; i < _this.detailslistExportlist.length; i++) {
                _this.detailslistExportlist[i].sumCardBalance = _this.amountyua(
                  _this.detailslistExportlist[i].sumCardBalance
                )
                _this.detailslistExportlist[i].avgCardBalance = _this.amountyua(
                  _this.detailslistExportlist[i].avgCardBalance
                )
                _this.detailslistExportlist[i].cardBalance = _this.amountyua(
                  _this.detailslistExportlist[i].cardBalance
                )
                _this.detailslistExportlist[i].balanceDiff = _this.amountyua(
                  _this.detailslistExportlist[i].balanceDiff
                )
              }
              resolve(_this.detailslistExportlist)
            } else {
              reject(data.errorMessage)
              _this.$message.error(data.errorMessage)
            }
          })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    export2Excel() {
      const nowtime = this.getimeto()
      require.ensure([], () => {
        const multiHeader = []
        const multiHeader2 = []
        const merges = []
        const { export_json_to_excel } = require('@/excel/Export2Excel')
        // tHeaderarr.push('部门名称')

        let tHeader = []
        let filterVal = []
        for (let key in this.formThead) {
          if (this.formThead[key].checked) {
            tHeader.push(this.formThead[key].label)
            filterVal.push(this.formThead[key].prop)
          }
        }

        const list = this.detailslistExportlist
        const data = this.formatJson(filterVal, list)
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename + nowtime
        })
      })
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.detailspage()
    },
    handleCurrentChangepage(val) {
      this.pageNum = val
      this.detailspage()
    }
  }
}
</script>

<style lang="scss" scoped>
.swipe_details {
  padding: 10px;
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }

  .el-table__row .el-table__row--level-1 {
    background-color: #e5e9f2;
  }
  .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 5px;
  }
  /deep/.el-form.el-form--inline {
    /deep/.el-form-item.el-form-item--mini {
      margin-bottom: 5px;
    }
  }
  /deep/.el-button.el-button--text{
    padding: 0;
  }

  .page {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
/deep/.el-button.el-button--primary.el-button--mini.el-popover__reference{
  width: 73px;
}
/deep/.el-input.el-input--mini.el-input--suffix{
  margin-right: 1px;
}

</style>